<template>
  <div class="search">
    <form action="/">
      <van-search
        v-model.trim="value"
        show-action
        placeholder="请输入搜索关键词"
        @search="onSearch"
        @cancel="$router.back()"
        background="#3296fa"
        @focus="isShowRes=false"
      />
    </form>
    <search-results  v-if="isShowRes" :searchText="value"/>
    <search-history @clear="history=[]" @onSearch="onSearch" :history="history" v-else-if="!value"  />
    <search-suggestion @onSearch="suggestionSearch" :searchText="value" v-else/>
  </div>
</template>

<script>
import SearchHistory from './components/SearchHistory.vue'
import SearchResults from './components/SearchResults.vue'
import SearchSuggestion from './components/SearchSuggestion.vue'
import { setStorage, getStorage } from '@/utils/storage'
export default {
  components: { SearchHistory, SearchResults, SearchSuggestion },
  name: 'Search',
  data () {
    return {
      value: '',
      isShowRes: false,
      history: getStorage('TT-history') || []
    }
  },

  created () {

  },

  methods: {
    onSearch (val) {
      this.value = val
      this.isShowRes = true
      this.history.unshift(val)
      this.history = [...new Set(this.history)]
    },
    suggestionSearch (val) {
      this.value = val
    }
  },
  watch: {
    history: {
      deep: true,
      handler (val) {
        setStorage('TT-history', val)
      }
    }
  }
}
</script>

<style scoped lang='less'>
.search{
  .van-search__action{
    color: #fff;
  }
}
</style>
